#!/bin/bash 

# 检查参数
ROOT_DIR=$PWD
OUTPUT_DIR_Perf=$PWD/perf
OUTPUT_DIR_Test=$PWD/test
export skip_rc=4
export timeout_rc=124
export kselftest_default_timeout=120

# 删除已有输出结果
# rm -rf perf
# rm -rf test

# 创建输出目录（如果不存在）
mkdir -p "$OUTPUT_DIR_Perf"
mkdir -p "$OUTPUT_DIR_Test"
COUNT=0
count_file=$(mktemp)  # 创建临时文件来存储计数器

tap_timeout() {
    # Make sure tests will time out if utility is available.
    if [ -x /usr/bin/timeout ]; then
        /usr/bin/timeout --foreground "$kselftest_default_timeout" "$@"
    else
        "$@"
    fi
}

directories=("." "./riscv")  # 使用 bash 数组

# Iterate over the directories
for dir in "${directories[@]}"; do
    # Find all .c files in the specified directory (not including subdirectories)
    for src_file in "$dir"/*.c; do
        # Check if the .c file exists to avoid errors when no .c files are found
        [ -e "$src_file" ] || continue

        # Get the filename without the extension
        executable="${src_file%.c}"

        # Check if the corresponding executable exists and is a file
        if [ -f "$executable" ] && [ -x "$executable" ]; then
            executable="${executable#./}"
            echo "$executable"
            cmd="./$executable"
            file="$executable"

            if [ -f "$OUTPUT_DIR_Test/$file.txt" ]; then
                echo "the test $executable has completed"
            else
                #tap_timeout "$cmd" > "$file.txt" 2>&1
                "$cmd" > "$file.txt" 2>&1
                rc=$?
                if [ $rc -eq 0 ]; then
                    echo "ok $COUNT $executable" >> "$file.txt"
                else
                    if [ $rc -eq $skip_rc ]; then
                        echo "ok $COUNT $executable # SKIP" >> "$file.txt"
                    elif [ $rc -eq $timeout_rc ]; then
                        echo "not ok $COUNT $executable # TIMEOUT $kselftest_default_timeout seconds" >> "$file.txt"
                    else
                        echo "not ok $COUNT $executable # exit=$rc" >> "$file.txt"
                    fi
                fi  # 关闭 if

                mv "$file.txt" "$OUTPUT_DIR_Test"
            fi  # 关闭 if
            
            # 调用 perf 脚本
            if [ -f "$OUTPUT_DIR_Perf/$file.txt" ]; then
                echo "the perf test has completed"
            else
                $ROOT_DIR/perf.sh "$cmd" "$OUTPUT_DIR_Perf" "$executable"
            fi  # 关闭 if
            
            COUNT=$((COUNT + 1))
            echo "$COUNT" > "$count_file"
            echo "$COUNT $executable"
            echo ""
        fi  # 关闭 if
    done  # 关闭 inner for
    COUNT=$(cat "$count_file")
done  # 关闭 outer for

COUNT=$(cat "$count_file")
rm "$count_file"
echo "Total number of tests completed: $COUNT"
